package com.nari.interplatform.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/23.
 */
public class HttpUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(com.nari.interplatform.utils.HttpUtil.class);

    private static final String SERVER_URL = "http://xx.xx.xx.xx:xx";
    private static final String SERVER_APP = "/application_service";
    private static final String SERVLET_POST = "POST";
    private static final String SERVLET_GET = "GET";
    private static final String SERVLET_DELETE = "DELETE";
    private static final String SERVLET_PUT = "PUT";


    private HttpUtil(){}
    /**
     * 处理参数 ->url参数
     * @param paramMap   参数
     * @return
     */
    private static String prepareParam(Map<String, Object> paramMap) {
        StringBuffer sb = new StringBuffer();
        try{
            if (paramMap.isEmpty()) {
                return "";
            } else {
                for (String key : paramMap.keySet()) {
                    String value = (String) paramMap.get(key).toString();
                    if (sb.length() < 1) {
                        sb.append(key).append("=").append(URLEncoder.encode(value, "UTF-8"));
                    } else {
                        sb.append("&").append(key).append("=").append(URLEncoder.encode(value, "UTF-8"));
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getLocalizedMessage(),e);
        }
        return sb.toString();
    }

    /**
     * post请求
     * @param urlStr     url地址
     * @param paramMap   url参数
     * @return
     * @throws Exception 请求异常
     */
    public static String doPost(String urlStr, Map<String, Object> paramMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        HttpURLConnection conn =null;
        String result = "";
        try {
            URL url = new URL(urlStr);
            String paramStr = prepareParam(paramMap);
            // 打开和URL之间的连接
            conn = (HttpURLConnection) url.openConnection();
            //设置属性
            conn.setRequestMethod(SERVLET_POST);
            // 发送POST请求必须设置如下两行
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // 获取URLConnection对象对应的输出流
            conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3");
            conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            conn.setRequestProperty("Accept-Language","zh-cn,zh;q=0.5");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            conn.addRequestProperty("Content-Length", paramStr.length() + "");
            conn.connect();
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.write(paramStr);
            // flush输出流的缓冲
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            LOGGER.error("发送 POST 请求出现异常！" + e);
            LOGGER.error(e.getLocalizedMessage(),e);
        }// 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                LOGGER.error(e.getLocalizedMessage(),e);
            }
        }
        return result;
    }

    /**
     * get请求
     * @param urlStr          url地址
     * @param paramMap        url参数
     * @return
     * @throws Exception
     */
    public static String doGet(String urlStr, Map<String, Object> paramMap)
            throws Exception {
        String paramStr = prepareParam(paramMap);
        if (paramStr == null || paramStr.trim().length() < 1) {

        } else {
            urlStr += "?" + paramStr;
        }
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(SERVLET_GET);
        conn.setRequestProperty("Content-Type", "text/html; charset=UTF-8");

        conn.connect();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String line;
        String result = "";
        while ((line = br.readLine()) != null) {
            result += line;
        }
        br.close();
        return result;
    }


    /**
     * put请求
     * @param urlStr
     * @param paramMap
     * @return
     * @throws Exception
     */
    public static String doPut(String urlStr, Map<String, Object> paramMap)
            throws Exception {
        PrintWriter out = null;
        BufferedReader in = null;
        HttpURLConnection conn =null;
        String result = "";
        try {
            URL url = new URL(urlStr);
            String paramStr = prepareParam(paramMap);
            // 打开和URL之间的连接
            conn = (HttpURLConnection) url.openConnection();
            //设置属性
            conn.setRequestMethod(SERVLET_PUT);
            // 发送POST请求必须设置如下两行
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // 获取URLConnection对象对应的输出流
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            conn.addRequestProperty("Content-Length", paramStr.length() + "");
            conn.connect();
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.write(paramStr);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            if(conn.getResponseCode() == 200){
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            }else{
                result = String.valueOf(conn.getResponseCode());
            }
        } catch (Exception e) {
            LOGGER.error("发送 PUT 请求出现异常！" + e);
            LOGGER.error(e.getLocalizedMessage(),e);
        }// 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                LOGGER.error(e.getLocalizedMessage(),e);
            }
        }
        return result;
    }

    /**
     * Delete请求
     * @param urlStr
     * @param paramMap
     * @throws Exception
     */
    public static int doDelete(String urlStr, Map<String, Object> paramMap)
            throws Exception {
        String paramStr = prepareParam(paramMap);
        if (paramStr == null || paramStr.trim().length() < 1) {

        } else {
            urlStr += "?" + paramStr;
        }
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(SERVLET_DELETE);
        conn.connect();
        return conn.getResponseCode();
    }
    /**
     * 发送post请求
     * @param url  路径
     * @param jsonObject  参数(json类型)
     * @param encoding 编码格式
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String send(String url, JSONObject jsonObject, String encoding) throws ParseException, IOException {
        String body = "";

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //装填参数
        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        //设置参数到请求对象中
        httpPost.setEntity(s);
        System.out.println("请求地址："+url);
//        System.out.println("请求参数："+nvps.toString());

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
//        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }


    public static String getServerUrl() {
        return SERVER_URL;
    }

    public static String getServerApp() {
        return SERVER_APP;
    }

    public static String getServletPost() {
        return SERVLET_POST;
    }

    public static String getServletGet() {
        return SERVLET_GET;
    }

    public static String getServletDelete() {
        return SERVLET_DELETE;
    }

    public static String getServletPut() {
        return SERVLET_PUT;
    }

}
